#!/usr/bin/env python3
"""
CAN信号接收器
功能：接收CAN信号并进行校验
"""

import can
import time
import struct

# 定义8种车辆信号（与发送器保持一致）
SIGNALS = [
    {"name": "发动机转速", "id": 0x100, "min": 800, "max": 6000, "unit": "rpm"},
    {"name": "车速", "id": 0x101, "min": 0, "max": 200, "unit": "km/h"},
    {"name": "发动机温度", "id": 0x102, "min": 70, "max": 110, "unit": "°C"},
    {"name": "燃油量", "id": 0x103, "min": 0, "max": 100, "unit": "%"},
    {"name": "电池电压", "id": 0x104, "min": 11.0, "max": 14.5, "unit": "V"},
    {"name": "节气门位置", "id": 0x105, "min": 0, "max": 100, "unit": "%"},
    {"name": "制动压力", "id": 0x106, "min": 0, "max": 100, "unit": "%"},
    {"name": "转向角度", "id": 0x107, "min": -540, "max": 540, "unit": "度"},
]

def validate_signal(sig, value):
    """校验信号值是否在正常范围内"""
    if sig["min"] <= value <= sig["max"]:
        print(f"✅ {sig['name']}: {value:.2f} {sig['unit']} (正常)")
    else:
        print(f"❌ {sig['name']}: {value:.2f} {sig['unit']} (超出范围 {sig['min']}-{sig['max']})")

def main():
    print("📥 CAN信号接收器启动")
    print("正在监听虚拟CAN通道...")
    print("等待信号...\n")
    
    # 连接到虚拟CAN通道
    bus = can.interface.Bus(interface='virtual', channel='can0', bitrate=500000)
    
    try:
        while True:
            # 接收CAN消息
            msg = bus.recv(timeout=1.0)
            
            if msg is None:
                continue
                
            # 查找对应的信号定义
            sig = next((s for s in SIGNALS if s["id"] == msg.arbitration_id), None)
            
            if sig:
                # 解析信号值
                try:
                    value = struct.unpack('f', msg.data)[0]
                    print(f"📥 接收: {sig['name']} - ID:0x{sig['id']:03X}, 数据:{msg.data.hex()}")
                    # 校验信号
                    validate_signal(sig, value)
                except struct.error:
                    print(f"❌ 数据解析失败: {sig['name']} - 数据:{msg.data.hex()}")
            else:
                print(f"⚠️ 收到未知信号: ID:0x{msg.arbitration_id:03X}, 数据:{msg.data.hex()}")
            
    except KeyboardInterrupt:
        print("\n⏹️ 接收器已停止")
    finally:
        bus.shutdown()

if __name__ == "__main__":
    main() 